<template>
  <div class="app-container">
    <el-row>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="hanldCreate"
      >
        {{ $t("table.add") }}
      </el-button>
    </el-row>

    <el-row>
      <el-table :data="roles" style="width: 100%">
        <el-table-column prop="code" label="编码"> </el-table-column>
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="{ row }">
            <i v-if="row.status == 1" class="el-icon-check" />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"> </el-table-column>
        <el-table-column prop="updateTime" label="修改时间"> </el-table-column>
        <el-table-column
          :label="$t('table.actions')"
          align="center"
          width="230"
          class-name="fixed-width"
        >
          <template slot-scope="{ row }">
            <template v-if="row.code != 'ROOT'">
              <el-button
                icon="el-icon-edit"
                @click="handlModify(row)"
                circle
              ></el-button>
              <el-button
                @click="destory(row)"
                icon="el-icon-delete"
                circle
              ></el-button>
            </template>
            <template v-else><span style="color:red;font-weight:bold;">系统通用角色</span></template>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog title="编辑角色信息" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tmpModel"
        :close-on-click-modal="false"
        label-position="left"
        label-width="100px"
        style="width: auto; margin-left: 50px"
      >
        <el-form-item label="编码" prop="code">
          <el-input v-model="tmpModel.code" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="tmpModel.name" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-checkbox
            :true-label="1"
            :false-label="0"
            v-model="tmpModel.status"
            >启用/停用</el-checkbox
          >
        </el-form-item>
        <el-form-item
          v-for="item in key2permission"
          v-bind:key="item.grp"
          :label="item.grp"
        >
          <el-checkbox-group v-model="item.checkedLs">
            <el-checkbox
              v-for="it in item.ls"
              :label="it.id"
              :indeterminate="it.indeterminate"
              :disabled="it.required"
              v-bind:key="it.id"
              @change="handleChange(it)"
              >{{ it.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t("table.cancel") }}
        </el-button>
        <el-button type="primary" @click="editData">
          {{ $t("table.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import {
  compayLs,
  saveCompany,
  destoryCompany,
  roleList,
  sysPermission,
  user2role,
  role2perm,
  saveRole2permission,
  destoryRoleById,
} from "@/api/users";
import { cloneDeep } from "lodash";
import { Form } from "element-ui";
import { parseTime } from "@/utils";
import { number } from "echarts";
import TabPane from "@/views/tab/components/TabPane.vue";
@Component({
  name: "SysRole",
  components: {TabPane},
})
export default class extends Vue {
  private dialogFormVisible: boolean = false;

  private defaultModel = {
    status: 1,
    createTime: parseTime(new Date()),
    updateTime: parseTime(new Date()),
  };
  private tmpModel: any = this.defaultModel;

  mounted() {
    this.loadRoleLs();
  }
  private hanldCreate() {
    this.tmpModel = cloneDeep(this.defaultModel);
    this.dialogFormVisible = true;
    this.loadSysPermission(0);
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }

  private destory(row: any) {
    this.$confirm("删除将不可恢复，您确定要删除吗？").then(async (val: any) => {
      let d = await destoryRoleById([row.id]);
      this.loadRoleLs();
      this.$message({
        message: "删除成功",
        type: "success",
      });
    });
  }

  private handlModify(row: any) {
    this.tmpModel = cloneDeep(row);
    this.dialogFormVisible = true;
    this.loadSysPermission(row.id);
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }

  private handleChange(it: any) {
    // console.log(it);

    for (let o of this.key2permission) {
      let ts = o.ls.filter((it2: any) => it2 == it);
      if (ts.length > 0) {
        if (it.id == 0) {
          let item = ts[0];
          if (o.checkedLs.includes(item.id)) {
            o.ls
              .map((it2: any) => it2.id)
              .forEach((it2: any) => {
                if (it2) o.checkedLs.push(it2);
              });
          } else {
            o.checkedLs = [];
          }
        }
        o.ls[0].indeterminate =
          o.ls.length - 1 == o.checkedLs.filter((it2: any) => it2 > 0).length;
      }
    }

    if (it.id == 0) {
    }
  }
  private editData() {
    (this.$refs.dataForm as Form).validate(async (valid) => {
      if (valid) {
        const model = this.tmpModel;
        let persSet = new Set();
        model.updateTime = parseTime(new Date());

        for (let o of this.key2permission) {
          o.checkedLs.forEach((it: any) => {
            persSet.add({ roleId: model.id, permissionId: it });
          });
        }
        const { data } = await saveRole2permission({
          role: model,
          ls: Array.from(persSet),
        });
        this.$message({
          message: "操作成功",
          type: "success",
        });
        this.dialogFormVisible = false;
        this.loadRoleLs();
      }
    });
  }
  private rules = {
    code: [
      {
        required: true,
        message: "编码不能为空且要保持唯一",
        trigger: "blur",
      },
      { min: 3, max: 255, message: "编码长度在3到255个字符", trigger: "blur" },
    ],
    name: [
      { required: true, message: "名称不能为空且要保持唯一", trigger: "blur" },
      { min: 3, max: 500, message: "名称长度在3到500个字符", trigger: "blur" },
    ],
  };

  private roles: Array<any> = [];
  private key2permission: Array<any> = [];

  private permissionLs: Array<any> = [];

  private async loadSysPermission(rid: number) {
    // const { data } = await sysPermission({});
    let r2ps: any = await role2perm({});
    r2ps = r2ps.data;
    r2ps = r2ps.filter((it: any) => it.roleId == rid);
    console.log(r2ps);

    //按资源组显示列表
    if (this.permissionLs) {
      let ls = this.permissionLs;

      let obj: any = {};
      for (let o of ls) {
        obj[o.grp] = obj[o.grp] || [];
        if (obj[o.grp].length == 0) {
          obj[o.grp].push({ id: 0, name: "全选", indeterminate: false });
        }
        obj[o.grp].push(o);
      }
      let ts: Array<any> = [];
      let permsIds: Array<any> = r2ps.map((it: any) => it.permissionId);

      Object.keys(obj).forEach((val: string, index: number) => {
        let o: any = { grp: val, ls: obj[val], checkedLs: [] };
        //选中的个数
        o.checkedLs =
          o.ls
            .filter((it: any) => permsIds.includes(it.id))
            .map((it: any) => it.id) || [];

        //选中必选滴：
        o.ls
          .filter((it2: any) => it2.required)
          .map((it2: any) => it2.id)
          .forEach((val: any) => {
            o.checkedLs.push(val);
          });
        //全选样式：
        o.ls[0].indeterminate = o.checkedLs.length == o.ls.length - 1;
        ts.push(o);
      });

      this.key2permission = ts;
    }
  }
  private async loadRoleLs() {
    const { data } = await roleList({});
    this.roles = data;

    let d: any = await sysPermission({});
    d = d.data;

    this.permissionLs = d;
  }
}
</script>
<style lang="scss" scoped>
</style>